package com.atguigu.jinx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.jinx.entity.pojo.OrderInfo;
import com.atguigu.jinx.entity.pojo.QueryVo;
import com.atguigu.jinx.entity.pojo.RefundInfo;
import com.atguigu.jinx.entity.vo.PayVo;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Optional;

@ConfigurationProperties(prefix = "alipay")
@Component
@Data
@PropertySource("classpath:alipay.properties")
@Slf4j
public class AlipayTemplate {

    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    private String app_id;

    // 商户私钥，您的PKCS8格式RSA2私钥
    private String merchant_private_key;

    // 应用公钥
    private String application_public_key;

    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private String alipay_public_key;

    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    private String notify_url;

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    //同步通知，支付成功，一般跳转到成功页
    private String return_url;

    // 签名方式
    private String sign_type;

    // 字符编码格式
    private String charset;

    //订单超时时间
    private String timeout = "3m";

    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
    public String gatewayUrl;

    public String pay(PayVo vo) throws AlipayApiException {

        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, application_public_key, sign_type);

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", out_trade_no);
        jsonObject.put("total_amount", total_amount);
        jsonObject.put("subject", subject);
        jsonObject.put("body", body);
        jsonObject.put("timeout_express", timeout);
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
 /*       HashMap<String, String> stringStringHashMap = new HashMap<>(2);
        stringStringHashMap.put("hb_fq_num", "3");
        stringStringHashMap.put("hb_fq_seller_percent", "100");
        jsonObject.put("extend_params", stringStringHashMap);*/
        alipayRequest.setBizContent(jsonObject.toJSONString());
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        return result;

    }

    @SneakyThrows
    /**
     * 查询接口
     */
    public String queryOrder(QueryVo vo) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "    \"out_trade_no\":\"" + vo.getOut_trade_no() + "\"," +
                    "    \"trade_no\":\"" + vo.getTrade_no() + "\"" +
                    "  }");
            AlipayTradeQueryResponse response = alipayClient.execute(request);

            if (response.isSuccess()) {
                log.info("调用成功");
                return response.getBody();
            } else {
                log.info("调用失败");
                return response.getBody();
            }
        } catch (AlipayApiException e) {
            log.error(e.getMessage());
            throw e;
        }
    }

    public Optional<String> refundOrder(RefundInfo orderInfo) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, application_public_key, sign_type);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orderInfo.getOrderNo());
        jsonObject.put("trade_no", orderInfo.getRefundId());
        jsonObject.put("refund_amount", orderInfo.getRefund());
        jsonObject.put("refund_reason", orderInfo.getReason());
        jsonObject.put("out_request_no", orderInfo.getRefundNo());
        request.setBizContent(jsonObject.toJSONString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return Optional.of(response.getBody());
        } else {
            System.out.println("调用失败");
            return Optional.ofNullable(null);
        }

    }

    public Optional<String> closeOrder(OrderInfo orderInfo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, application_public_key, sign_type);


        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", orderInfo.getOutTradeNo());
        bizContent.put("out_trade_no", orderInfo.getOrderNo());
        request.setBizContent(bizContent.toJSONString());
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return Optional.of(response.getBody());
        } else {
            System.out.println("调用失败");
            return Optional.empty();
        }

    }

    public Optional<String> queryBill(String tradeDate) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, application_public_key, sign_type);

        //根据request类型的不同发送给不同的url
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();

        request.setBizContent("{" +
                "  \"bill_type\":\"trade\"," +
                "  \"bill_date\":\"" + tradeDate + "\"" +
                "}");

        AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return Optional.of(response.getBillDownloadUrl());
        } else {
            System.out.println("调用失败");
            return Optional.empty();
        }

    }


    public void downloadBill(String downloadUrl) {

        //将接口返回的对账单下载地址传入urlStr
        String urlStr = downloadUrl;
        //指定希望保存的文件路径
        String filePath = "/Users/kuanggong/billurl";
        URL url = null;
        HttpURLConnection httpUrlConnection = null;
        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            url = new URL(urlStr);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setConnectTimeout(5 * 1000);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("CHARSET", "UTF-8");
            httpUrlConnection.connect();
            fis = httpUrlConnection.getInputStream();
            byte[] temp = new byte[1024];
            int b;
            fos = new FileOutputStream(new File(filePath));
            while ((b = fis.read(temp)) != -1) {
                fos.write(temp, 0, b);
                fos.flush();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) fis.close();
                if (fos != null) fos.close();
                if (httpUrlConnection != null) httpUrlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

